﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// InputPasswordPanel.xaml 的交互逻辑
    /// </summary>
    public partial class InputPasswordPanel : UserControl
    {
        /// <summary>
        /// [构造方法]此方法用于创建一个密码输入面板。此面板用于输入密码打开被加密的 Markdown 文档。
        /// </summary>
        /// <param name="masterEditor">宿主编辑器。</param>
        public InputPasswordPanel(MarkdownEditor masterEditor)
        {
            InitializeComponent();

            this.masterEditor = masterEditor;
        }

        /// <summary>
        /// 宿主编辑器。
        /// </summary>
        private MarkdownEditor masterEditor;

        /// <summary>
        /// 检验用户输入的密码是否正确。如果正确，打开文档（隐藏密码输入面板）。
        /// </summary>
        private void btnOpenDocument_Click(object sender, RoutedEventArgs e)
        {
            OpenDocument();
        }

        /// <summary>
        /// 检验用户输入的密码是否正确。如果正确，打开文档（隐藏密码输入面板）。
        /// </summary>
        private void OpenDocument()
        {
            // 如果只是锁定文件，直接隐藏就成了。
            if (this.masterEditor.IsModified)
            {
                if (this.tbxPassword.Password == this.masterEditor.Password)
                {
                    this.Visibility = Visibility.Collapsed;
                    return;
                }
            }

            if (string.IsNullOrEmpty(this.masterEditor.FullFilePath))
            {
                LMessageBox.Show("未提供有效文件名！", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (System.IO.File.Exists(this.masterEditor.FullFilePath) == false)
            {
                LMessageBox.Show(string.Format("　　不存在路径为{0}的文件\r\n", this.masterEditor.FullFilePath), Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //this.masterEditor.EditorBase.Load(this.masterEditor.FullFilePath);
            //要考虑加密，不能直接打开。

            var text = File.ReadAllText(this.masterEditor.FullFilePath);
            if (string.IsNullOrEmpty(text))
            {
                this.Visibility = Visibility.Collapsed;
                return;
            }

            string fstLine;
            var index = text.IndexOf("\r");
            if (index < 0)
            {
                fstLine = text;
            }
            else
            {
                fstLine = text.Substring(0, index);
            }

            var decryptedFstLine = SetPasswordPanel.TextDecrypt(
                fstLine.Replace("[[<r>]]", "\r").Replace("[[<n>]]", "\n").ToCharArray(), "DyBj#PpBb");
            var indexOfPassword = decryptedFstLine.IndexOf("Password:");
            var indexOfQuestion = decryptedFstLine.IndexOf("Question:");
            if (indexOfQuestion < 0 || indexOfPassword < 0)
            {
                this.Visibility = Visibility.Collapsed;
                return;
            }

            var password = decryptedFstLine.Substring(indexOfPassword + 9);

            if (tbxPassword.Password != password)
            {
                LMessageBox.Show("　　密码不正确！", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var content = text.Substring(index + 2);
            this.masterEditor.EditorBase.Document.Text = SetPasswordPanel.TextDecrypt(content.ToCharArray(), "DyBj#PpBb");

            //初始化文件保存状态。
            this.masterEditor.EditorBase.IsModified = false;
            this.Visibility = Visibility.Collapsed;

            //还得显示文件的标题.因为是加密文档，打开文档之前无法从文档中读取标题。
            masterEditor.UpdateTitleToHeader();
        }

        /// <summary>
        /// 关闭文档（放弃输入密码）。
        /// </summary>
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (Globals.MainWindow.mainTabControl.Items.Contains(this.masterEditor))
            {
                Globals.MainWindow.mainTabControl.Items.Remove(this.masterEditor);
            }
        }

        /// <summary>
        /// 删除文档密码。这需要知道旧密码。
        /// </summary>
        private void btnDeletePassword_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(this.masterEditor.FullFilePath) == false)
            {
                LMessageBox.Show("　　从未在磁盘上保存过该文件，没办法删除密码。", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (this.tbxPassword.Password == this.masterEditor.Password)
            {
                OpenDocument();
                //不先打开，则此时编辑器中无文本，自然无法保存。

                this.masterEditor.Password = this.masterEditor.PasswordTip = "";
                this.masterEditor.SaveDocument();
                this.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 回车键打开文档（隐藏密码输入面板）。
        /// </summary>
        private void tbxPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key== Key.Enter)
            {
                OpenDocument();
            }
        }
    }
}
